package com.zhxy.gps.publish;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.mina.core.service.AbstractIoAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.zhxy.util.message.JavaMessageCodec;
import com.zhxy.util.message.MinaDuplexMessageService;
import com.zhxy.util.publish.DuplexMessagePublisherRouter;

/**
 * 
 * @author 刘勉
 *
 */
public class MinaPublisherRouter<P> extends DuplexMessagePublisherRouter<P> {

	private MinaDuplexMessageService service;
	
	private ScheduledExecutorService scheduledExecutor;

	public void setScheduledExecutor(ScheduledExecutorService scheduledExecutor) {
		this.scheduledExecutor = scheduledExecutor;
	}

	public void bind(AbstractIoAcceptor acceptor, InetSocketAddress address) throws IOException {
		if (service != null)
			throw new IllegalStateException("服务已经启动");

		service = new MinaDuplexMessageService();
		service.setCodec(new JavaMessageCodec());
		service.setScheduledExecutor(scheduledExecutor);
		attach(service, true);
		service.bindIoService(acceptor);
		
		acceptor.bind(address);
	}
	
	public void connect(InetSocketAddress address) {
		if (service != null)
			throw new IllegalStateException("服务已经启动");
		
		NioSocketConnector c = new NioSocketConnector();
		
		service = new MinaDuplexMessageService();
		service.setCodec(new JavaMessageCodec());
		service.setScheduledExecutor(scheduledExecutor);
		attach(service, false);
		service.bindIoService(c);
		
		c.connect(address);
	}
	
	public void close() {
		if (service != null) {
			detach();
			service.close();
		}
	}
	

}
